package zinx

import (
	"awesomeProject/zinx/ziface"
	"errors"
	"fmt"
	"sync"
)

type ConnManager struct {
	connections map[uint32]ziface.IConnection
	connLock    sync.RWMutex
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
	}
}

func (cm *ConnManager) Add(conn ziface.IConnection) {
	fmt.Println("add connManager:",conn.GetConnId())
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	cm.connections[conn.GetConnId()] = conn

}
func (cm *ConnManager) Remove(conn ziface.IConnection) {
	fmt.Println("remove connManager:",conn.GetConnId())
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	delete(cm.connections, conn.GetConnId())
}

func (cm *ConnManager) Get(connId uint32) (ziface.IConnection, error) {
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	if conn, ok := cm.connections[connId]; ok {
		return conn, nil
	} else {
		return nil, errors.New("not found conn")
	}
}

func (cm *ConnManager) Len() int {
	return len(cm.connections)
}

func (cm *ConnManager) ClearConn() {
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	for connId, conn := range cm.connections {
		conn.Stop()
		delete(cm.connections, connId)
	}
}
